package com.csaba.swing.gui.login;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;

import com.csaba.connector.model.Bank;
import com.csaba.swing.gui.wizard.WizardModel;
import com.csaba.swing.gui.wizard.WizardPage;

public class LoginWizardModel implements WizardModel
{
	private static ServiceLoader<LoginWizardPages> serviceLoader = null;

	private static void initServiceLoader()
	{
		if ( serviceLoader == null )
		{
			serviceLoader = ServiceLoader.load(LoginWizardPages.class);
		}
	}

	private final List<WizardPage> pages = new ArrayList<WizardPage>();
	private Bank bank = null;
	private final Map<Bank, WizardPage[]> bankPages = new HashMap<Bank, WizardPage[]>();
	private boolean saveDetails = false;

	public LoginWizardModel()
	{
		pages.add(new BankSelectPage());
	}

	public Bank getBank()
	{
		return bank;
	}

	public void setBank( final Bank bank )
	{
		if ( bank.equals(this.bank) )
			return;

		//remove pages of the old bank 
		while ( pages.size() > 1 )
			pages.remove(1);

		this.bank = bank;

		WizardPage[] newPages = null;
		if ( bankPages.containsKey(bank) )
		{
			newPages = bankPages.get(bank);
		}
		else
		{
			//load pages for the bank
			initServiceLoader();

			for ( final LoginWizardPages plugin : serviceLoader )
			{
				if ( plugin.getBank().equals(bank) )
				{
					newPages = plugin.getPages();
					break;
				}
			}
			if ( newPages == null )
			{
				newPages = new WizardPage[] { new DefaultLoginPage() };
			}

			bankPages.put(bank, newPages);
		}

		for ( final WizardPage wizardPage : newPages )
		{
			pages.add(wizardPage);
		}
	}

	@Override
	public WizardPage getPageAt( final int index )
	{
		return pages.get(index);
	}

	@Override
	public int getPageCount()
	{
		return Math.max(2, pages.size());
	}

	public void setSaveDetails( final boolean saveDetails )
	{
		this.saveDetails = saveDetails;
	}

	public boolean isSaveDetails()
	{
		return saveDetails;
	}

}
